<?php
class IndexController extends Zend_Controller_Action
{
    public function preDispatch() 
    {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            if ($this->_request->getActionName() != 'login') {
                $this->_redirect('/user/login');
            }
        }
    }

	public function init()
    {
		parent::init();
		
		global $config;
        require_once ('function/function.php');
        require_once ('jpgraph/src/jpgraph.php');
        require_once ('jpgraph/src/jpgraph_bar.php');
        require_once ('jpgraph/src/jpgraph_line.php');
        require_once ('jpgraph/src/jpgraph_pie.php');
        require_once ('jpgraph/src/jpgraph_pie3d.php');
        require_once ('jpgraph/src/jpgraph_scatter.php');
        
        $front = Zend_Controller_Front::getInstance(); 
		$temp =$front->getParam('bootstrap')->getPluginResource('db');
		$option = $temp->getOptions(); 
		        
        mysql_connect($option['params']['host'], $option['params']['username'],$option['params']['password'])
         or die ("Could not connect to database"); 
        mysql_select_db($option['params']['dbname']) or die ("Could not select database");
       
	}

	public function indexAction()
	{ 
		global $config;
		$stock_code =$config["default_stock"];		
		$today = $config["today"];
		global $config;
        $auth = Zend_Auth::getInstance();
        $infoUser = $auth->getIdentity();  
        $this->view->uName = $infoUser->username;
        $this->view->rol = $infoUser-> role;
         		
		$company = new Application_Model_Company();
		$companies = $company->fetchAll();
		$this->view->companies = $companies;		
		$stock_code = $this->getRequest()->getParam("id");
		if(!$stock_code){
			$stock_code = $config["default_stock"];
		}
		$this->view->stock_code = $stock_code; 
        
	}
    
    public function graph1Action()
	{
		global $config;

        $stock_code =$config["default_stock"];
		$company = new Application_Model_Company();
        $stockdate = new Application_Model_StockDate();
        
        $request = $this->getRequest();
        if(!($stock_code = $request->getParam("id"))){
        	$stock_code = $config["default_stock"];           	
        }
        
        // @TASK: need change today here
        $today = mysql_result(mysql_query("SELECT max(`date`) FROM `index_growth`"),0,0);
        $previous_year = date("Y-m-d",strtotime('-1 year',strtotime($today)));
        $c = mysql_query("SELECT COUNT(`close`) FROM `index_growth` WHERE `ticker`='VNINDEX' AND `date` >= '$previous_year'");
        $vnindex = mysql_query("SELECT `close` FROM `index_growth` WHERE `ticker`='VNINDEX' AND `date` >= '$previous_year'");
        $ret = mysql_query("SELECT `dm_index_ret` FROM `cal_port` WHERE `date` >= '$previous_year'");
        $ret2 = mysql_query("SELECT `ret` FROM `stock_date` WHERE `ticker`='$stock_code' AND `date` >= '$previous_year'");
        $c2 = mysql_query("SELECT COUNT(`date`) FROM `stock_date` WHERE `ticker`='$stock_code' AND `date` >= '$previous_year'");
        
        $n  = mysql_result($c, 0, 0);
        $vnindex_value = array();
        $ret_value = array();
        $index = array();
        $index[0]= 1;
        for($i = 0; $i < $n; $i++){
            $ret_value[] = mysql_result($ret, $i, 0);
            $index[$i + 1] = $index[$i] * (1 + $ret_value[$i]);
            $vnindex_value[$i] = $index[$i] * 100;
   		}
        
        $n2 = mysql_result($c2, 0, 0);
        $gia_cophieu = array();
        $gia = array();
        $gia[0] = 1;
        $cophieu_value = array();
        for($j = 0; $j < $n2; $j++){
            $gia_cophieu[] = mysql_result($ret2, $j, 0);
            $gia[$j+1] = $gia[$j] * (1 + $gia_cophieu[$j]);
            $cophieu_value[$j] = $gia[$j] * 100;
   		}
        
        $data1 = array();
        $data2 = array();
        $data1 = $vnindex_value;
        $data2 = $cophieu_value;
        // Create the graph. These two calls are always required
        $graph = new Graph(350,250);
        $graph->SetScale("textlin", 40, 140);
        // set major and minor tick positions manually
        $graph->SetBox(true);
        
        //$graph->ygrid->SetColor('gray');
        $graph->ygrid->SetFill(false);
        $graph->yaxis->HideLine(false);
        $graph->yaxis->HideTicks(false,false);
        $graph->xaxis->HideLabels(true);
        
        // Create the bar plots
        $p1 = new LinePlot($data1);
        $p2 = new LinePlot($data2);
        
        // ...and add it to the graPH
        $graph->Add($p1);
        $graph->Add($p2);
        
        $p1->SetColor("red");
        $p1->SetLegend('VN-Index');
        $p1->SetCenter();
        
        $p2->SetColor("blue");
        $p2->SetLegend('Cổ phiếu');
        $p2->SetCenter();
        
        // Display the graph
        $graph->Stroke();
        $this->view->graph = $graph;
	}
    public function graph2Action()
    {
    	global $config;
        $sql = mysql_query("SELECT `ticker`,cr.`hsrr`,st.`close`,cr.`quantile_1`,cr.`so_ngay_tk` FROM `stock_date` st,`cal_risk` cr  WHERE cr.`stock_date_id` = st.`id` ORDER by cr.`hsrr` ASC LIMIT 0,10");
        $hsrr = array(10);
        $ticker = array(10);
        for($i=0; $i <10 ; $i ++)
        {
            $hsrr[$i] = mysql_result($sql,$i,1);
            $ticker[$i] = mysql_result($sql,$i,0);
        }
        
        $request = $this->getRequest();        
        if(!($ticker1 = $request->getParam("id")))
        	$ticker1 = $config["default_stock"];           	
        $sql = mysql_query("SELECT cr.`hsrr`, cr.`stock_code` FROM `stock_date` st,`cal_risk` cr  WHERE cr.`stock_date_id` = st.`id` AND cr.`stock_code` = '".$ticker1."'");        
        $hsrr1 = mysql_result($sql, 0, 0);        
        
        $hsrr_10_max = $hsrr[9]; 
                
       	$max_x = round($hsrr1,2);
       	if($hsrr_10_max > $hsrr1)
       		$max_x = round($hsrr_10_max+0.01,2);
       		
        $datay = array();        
        // Create the graph. These two calls are always required
        $datay = $hsrr;
        $graph = new Graph(200,230,'auto');
        $graph->SetScale("textlin",0,$max_x);
        $graph->yaxis->SetTickPositions(array(0.0, $max_x/2, $max_x));
        $tk = array();
        $tk[] = $ticker;
        $graph->xaxis->SetTickLabels($tk[0]);
        
        $graph->Set90AndMargin(0,20,4,20);
        $graph->img->SetAngle(90); 
        
        // set major and minor tick positions manually
        $graph->SetBox(false);
        $graph->ygrid->Show(false);
        $graph->ygrid->SetFill(false);
        $graph->yaxis->HideLine(false);
        $graph->yaxis->HideTicks(false,false);
        
        // For background to be gradient, setfill is needed first.
        //$graph->SetBackgroundGradient('#00CED1', '#FFFFFF', GRAD_HOR, BGRAD_PLOT);
        
        // Create the bar plots
        $b1plot = new BarPlot($datay);
        
        // ...and add it to the graPH
        $graph->Add($b1plot);
        
        $b1plot->SetWeight(0);
        $b1plot->SetFillGradient("blue","blue",GRAD_HOR);
        $b1plot->SetWidth(7);
        
        // Display the graph
        $graph->Stroke();
        $this->view->graph = $graph;
    }
     
    public function graph3Action()
    {
        $today = mysql_result(mysql_query("SELECT max(`date`) FROM `index_growth`"),0,0);
        $previous_year = date("Y-m-d",strtotime('-1 year',strtotime($today)));
        $c = mysql_query("SELECT COUNT(`close`) FROM `index_growth` WHERE `ticker`='VNINDEX' AND `date` >= '$previous_year'");
        $vnindex = mysql_query("SELECT `close` FROM `index_growth` WHERE `ticker`='VNINDEX' AND `date` >= '$previous_year'");
        $ret = mysql_query("SELECT `dm_index_ret` FROM `cal_port` WHERE `date` >= '$previous_year'");
        
        $n  = mysql_result($c, 0, 0);
        $vnindex_value = array();
        $ret_value = array();
        $index = array();
        $index[0]= 1;
        for($i = 0; $i < $n; $i++){
            $ret_value[] = mysql_result($ret, $i, 0);
            $index[$i + 1] = $index[$i] * (1 + $ret_value[$i]);
            $vnindex_value[$i] = $index[$i] * 100;
   		}
        
        $sql = "SELECT `data` FROM `index_port` order by `date` DESC LIMIT 0,1";
    	$res = mysql_query($sql);
    	$dm_index = unserialize(mysql_result($res,0,0));
    	$ret_values = array();
    	$port = array();
    	for($i = 0 ; $i < count($dm_index);$i++){		
    		$result_ret = array();
    		$sql = "SELECT `date`, `ret` from `stock_date` where `ticker`='{$dm_index[$i][0]}' and `date` BETWEEN '{$previous_year}' AND '{$today}'";
    		$res = mysql_query($sql);
    		while($r = mysql_fetch_object($res)){
    			$result_ret[$r->date] = $r->ret; 
    		}
    		$ret_values[$i] = $result_ret;
    	}
    	$j = 0;
    	
    	foreach($ret_values[0] as $key=>$value){
    		if(count($port)==0){
    			$port[] = 1;
    			continue;
    		}
    		$j++;
    		$total = $value*$dm_index[0][3] +1;
    		
    		for($i = 1; $i < 5; $i++){
    			$total+=$ret_values[$i][$key]*$dm_index[$i][3];
    		}			
    						
    		$total = $port[count($port)-1]*$total;		
    		$port[] = $total;
    	}	
    	
    	$ret_port = array();
        $dmindex_value = array();
    	$ret_port[] = 0;
    	$n  = count($port);
        for($i = 1; $i < $n; $i++){
    		$ret_port[] = $port[$i]/$port[$i-1]-1;
            $dmindex_value[] = $port[$i] * 100;
    	}
        if($this->getRequest()->get('custom_stock_1'))
        $d1 = mysql_query("SELECT `ret` FROM `stock_date` WHERE `ticker`='".$this->getRequest()->get('custom_stock_1')."' AND `date` >= '$previous_year'");
        if($this->getRequest()->get('custom_stock_2'))
        $d2 = mysql_query("SELECT `ret` FROM `stock_date` WHERE `ticker`='".$this->getRequest()->get('custom_stock_2')."' AND `date` >= '$previous_year'");
        if($this->getRequest()->get('custom_stock_3'))
        $d3 = mysql_query("SELECT `ret` FROM `stock_date` WHERE `ticker`='".$this->getRequest()->get('custom_stock_3')."' AND `date` >= '$previous_year'");
        if($this->getRequest()->get('custom_stock_4'))
        $d4 = mysql_query("SELECT `ret` FROM `stock_date` WHERE `ticker`='".$this->getRequest()->get('custom_stock_4')."' AND `date` >= '$previous_year'");
        if($this->getRequest()->get('custom_stock_5'))
        $d5 = mysql_query("SELECT `ret` FROM `stock_date` WHERE `ticker`='".$this->getRequest()->get('custom_stock_5')."' AND `date` >= '$previous_year'");
        $line1 = array();
        $line2 = array();
        $line3 = array();
        $line4 = array();
        $line5 = array();
        for($j = 0; $j < $n-1; $j++){
            if($this->getRequest()->get('custom_stock_1'))
    		$line1[] = mysql_result($d1, $j, 0);
            if($this->getRequest()->get('custom_stock_2'))
            $line2[] = mysql_result($d2, $j, 0);
            if($this->getRequest()->get('custom_stock_3'))
            $line3[] = mysql_result($d3, $j, 0);
            if($this->getRequest()->get('custom_stock_4'))
            $line4[] = mysql_result($d4, $j, 0);
            if($this->getRequest()->get('custom_stock_5'))
            $line5[] = mysql_result($d5, $j, 0);
    	}
        $port2 = array();
        $port2[0]= 1;
        $dmtuchon_value = array();
        for($k = 0; $k < $n-1; $k++){
            $port2[$k + 1] = $port2[$k];
            if($this->getRequest()->get('custom_stock_1'))
            $port2[$k + 1] +=  $line1[$k] * $this->getRequest()->get('custom_per_1') / 100;
            if($this->getRequest()->get('custom_stock_2'))
            $port2[$k + 1] +=  $line1[$k] * $this->getRequest()->get('custom_per_2') / 100;
            if($this->getRequest()->get('custom_stock_3'))
            $port2[$k + 1] +=  $line1[$k] * $this->getRequest()->get('custom_per_3') / 100;
            if($this->getRequest()->get('custom_stock_4'))
            $port2[$k + 1] +=  $line1[$k] * $this->getRequest()->get('custom_per_4') / 100;
            if($this->getRequest()->get('custom_stock_5'))
            $port2[$k + 1] +=  $line1[$k] * $this->getRequest()->get('custom_per_5') / 100;
            $dmtuchon_value[] = $port2[$k] * 100;
   		}
        
        $data1 = $dmindex_value;
        $data2 = $vnindex_value;
        $data3 = $dmtuchon_value;
        // Create the graph. These two calls are always required
        $graph = new Graph(350,180);
        $graph->SetScale("textlin", 60, 140);
        $graph->SetBox(true);
        $graph->title->Set('Diễn biến DM tự chọn và DM Index');
        // set major and minor tick positions manually

        //$graph->ygrid->SetColor('gray');
        $graph->ygrid->SetFill(false);
        //$graph->xaxis->SetTickLabels(array('A','B','C','D'));
        $graph->yaxis->HideLine(false);
        $graph->yaxis->HideTicks(false,false);
        $graph->xaxis->Hide(true);
        
        // Create the bar plots
        $line1 = new LinePlot($data1);
        $line2 = new LinePlot($data2);
        $line3 = new LinePlot($data3);
        
        // ...and add it to the graPH
        $graph->Add($line1);
        $graph->Add($line2);
        $graph->Add($line3);
        
        $line1->SetColor("blue");
        $line1->SetLegend('DM Index');
        $line1->SetCenter();
        
        $line2->SetColor("red");
        $line2->SetLegend('VN Index');
        $line2->SetCenter();
        
        $line3->SetColor("green");
        $line3->SetLegend('DM Tự chọn');
        $line3->SetCenter();

        // Display the graph
        $graph->Stroke();
        $this->view->graph = $graph;
    }
    
    public function graph4Action()
    {
        $calrisk = new Application_Model_CalRisk();
        $where = array();
        $calrisks = $calrisk->fetchAll($where);
        $this->view->calrisks = $calrisks;
        $sumCao = 0;
        $sumTB = 0;
        $sumThap = 0;
        $sumRatThap = 0;
        foreach($calrisks as $tong)
            if($tong->_mVonThiTruong > 10000)
                $sumCao += $tong->_mVonThiTruong;
            else if($tong->_mVonThiTruong < 10000 and $tong->_mVonThiTruong > 2000)
                $sumTB += $tong->_mVonThiTruong;
            else if($tong->_mVonThiTruong > 200 and $tong->_mVonThiTruong < 2000)
                $sumThap += $tong->_mVonThiTruong;
            else if($tong->_mVonThiTruong < 200)
                $sumRatThap += $tong->_mVonThiTruong;
        // Some data
        $data = array($sumCao,$sumTB,$sumThap,$sumRatThap);
        
        // Create the Pie Graph. 
        $graph = new PieGraph(180,220);
        
        //$theme_class= new VividTheme;
        //$graph->SetTheme($theme_class);
        
        // Set A title for the plot
        $graph->title->Set("Phân bố theo vốn hóa");
        
        // Create
        $p1 = new PiePlot3D($data);
        $p1->value->Show(false);
        $p1->SetLegends(array('VH Cao', 'VH TB', 'VH Thấp', 'VH Rất thấp'));
        $p1->SetHeight(12);
        $graph->Add($p1);
        
        $graph->Stroke();
        $this->view->graph = $graph;
    }
    
    public function graph5Action()
    {
        $calport = new Application_Model_CalPort();
        $where = array();
        $datas = $calport->fetchAll($where, 'date ASC', 255);
        $data1 = array();
        $data2 = array();
        $data3 = array();
        $data4 = array();
        foreach($datas as $d1)
        {
            $data1[] = $d1->_mDmSmallMc;
        }
        foreach($datas as $d2)
        {
            $data2[] = $d2->_mDmMidMc;
        }
        foreach($datas as $d3)
        {
            $data3[] = $d3->_mDmLargeMc;
        }
        foreach($datas as $d4)
        {
            $data4[] = $d4->_mDmIndex;
        }

        // Create the graph. These two calls are always required
        $graph = new Graph(230,220);
        $graph->SetScale("textlin", 60, 140);
        // set major and minor tick positions manually
        $graph->SetBox(true);
        $graph->title->Set("Diễn biến DM theo vốn hóa");
        
        //$graph->ygrid->SetColor('gray');
        $graph->ygrid->SetFill(false);
        $graph->yaxis->HideLine(false);
        $graph->yaxis->HideTicks(false,false);
        $graph->xaxis->HideLabels(true);
        
        // Create the bar plots
        $p1 = new LinePlot($data1);
        $p2 = new LinePlot($data2);
        $p3 = new LinePlot($data3);
        $p4 = new LinePlot($data4);
        
        // ...and add it to the graPH
        $graph->Add($p1);
        $graph->Add($p2);
        $graph->Add($p3);
        $graph->Add($p4);
        
        $p1->SetColor("green");
        $p1->SetLegend('VH Cao');
        
        $p2->SetColor("red");
        $p2->SetLegend('VH TB');
        
        $p3->SetColor("blue");
        $p3->SetLegend('VH Thấp');
        
        $p4->SetColor("#808080");
        $p4->SetLegend('VN Index');
        
        // Display the graph
        $graph->Stroke();
        $this->view->graph = $graph;
    }
    
    public function graph6Action()
    {
    	global $config;
        $stock_code =$config["default_stock"];
		$today = $config["today"];
        $current_stock_code = $stock_code;
        
        // @TASK: change here. INSTEAD OF SELECT MAX YEAR
        $today = mysql_result(mysql_query("SELECT max(`date`) FROM `index_growth`"),0,0);
        $previous_year = date("Y-m-d",strtotime('-1 year',strtotime($today)));
        $ck = $current_stock_code;
        $row1col1 = mysql_query("SELECT cr.`ret_12m` FROM `cal_risk`cr, `stock_date`st WHERE st.`ticker`='$ck' AND st.`date` = '$today' AND cr.`stock_date_id` = st.`id`");
        $loi_nh = mysql_result($row1col1,0,0);
        $dayy = date('Y-m-d', strtotime($today));
        $nam_truoc = strtotime ('-1 year' , strtotime ($dayy));
        $ngay = date("Y-m-d",$nam_truoc);
        $row5col1 = mysql_query("SELECT `dm_large_mc`,`dm_mid_mc`,`dm_small_mc` FROM `cal_port` WHERE `date` = '$dayy' ");
        $vn_ht = mysql_result(mysql_query("SELECT `close` FROM `index_growth` WHERE `date`= '$dayy' AND `ticker`='VNINDEX' "),0,0);
        $hn_ht = mysql_result(mysql_query("SELECT `close` FROM `index_growth` WHERE `date`= '$dayy' AND `ticker`='HNXINDEX' "),0,0);                             
        $res = mysql_query("SELECT `close` FROM `index_growth` WHERE `date`= '$ngay' AND `ticker`='VNINDEX'");
        $res1 = mysql_query("SELECT `close` FROM `index_growth` WHERE `date`= '$ngay' AND `ticker`='HNXINDEX'");
        $res2 = mysql_query("SELECT `close` FROM `index_growth` WHERE `date`= '$ngay' AND `ticker`='SP500'");
        $res3 = mysql_query("SELECT `close` FROM `index_growth` WHERE `date`= '$ngay' AND `ticker`='HANGSENG'");
        $vn_namtruoc = mysql_result($res,0,0);
        $hn_namtruoc = mysql_result($res1,0,0);
        $sql = "SELECT `close`,`date` FROM `index_growth` WHERE `ticker`='SP500' order by `date` DESC LIMIT 0,1 ";                                            
        $sp_ht = mysql_result(mysql_query($sql),0,0);   
        $sp_namtruoc = mysql_result($res2,0,0);   
        $sh_ht = mysql_result(mysql_query("SELECT `close` FROM `index_growth` WHERE `ticker`='HANGSENG' order by `date` DESC LIMIT 0,1"),0,0);                                                                          
        $sh_namtruoc = mysql_result($res3,0,0);
        
        $s = mysql_query("SELECT cr.`vol_12m` FROM `stock_date` st,`cal_risk` cr  WHERE cr.`stock_date_id` = st.`id` AND st.`ticker`='$ck'");
        $dlc = (mysql_result($s,0,0)*sqrt(250)*100);
        $g = mysql_query("SELECT COUNT(`dm_large_mc_ret`) FROM `cal_port`"); 
        $h = mysql_query("SELECT `dm_large_mc_ret`,`dm_mid_mc_ret`,`dm_small_mc_ret`,`dm_index_ret` FROM `cal_port`");
        $g1 = mysql_query("SELECT COUNT(`close`) FROM `index_growth` WHERE `ticker`='HNXINDEX' AND `date` >= '$previous_year'");
        $g2 = mysql_query("SELECT COUNT(`close`) FROM `index_growth` WHERE `ticker`='SP500' AND `date` >= '$previous_year'");
        $g3 = mysql_query("SELECT COUNT(`close`) FROM `index_growth` WHERE `ticker`='HANGSENG' AND `date` >= '$previous_year'");
                                            
        $k = mysql_query("SELECT `close` FROM `index_growth` WHERE `ticker`='HNXINDEX' AND `date` >= '$previous_year'");
        $k2 = mysql_query("SELECT `close` FROM `index_growth` WHERE `ticker`='SP500' AND `date` >= '$previous_year'");
        $k3 = mysql_query("SELECT `close` FROM `index_growth` WHERE `ticker`='HANGSENG' AND `date` >= '$previous_year'");
                                                                           
        $count = mysql_result($g,0,0);
        $count1 = mysql_result($g1,0,0);
        $count2 = mysql_result($g2,0,0);
        $count3 = mysql_result($g3,0,0);
                                            
        $g_arr = array($count-1);
        $h_arr = array($count-1);
        $i_arr = array($count-1);
        $j_arr = array($count-1);
        $k_arr = array($count1-1);
        $k2_arr = array($count2-1);
        $k3_arr = array($count3-1);
                                            
        for($i = 0; $i < $count ;$i++)
        {
            $g_arr[$i] = mysql_result($h,$i,0)*100;
            $h_arr[$i] = mysql_result($h,$i,1)*100;    
            $i_arr[$i] = mysql_result($h,$i,2)*100;
            $j_arr[$i] = mysql_result($h,$i,3)*100;                                                
        }
        $k_arr[0] = 0;
        for ($j = 1; $j < $count1; $j++ )
        {
            $a1 = mysql_result($k,$j-1,0);
            $b1 = mysql_result($k,$j,0);                                    
            $k_arr[$j] = (($b1-$a1)/$a1)*100;        
        }
        $k2_arr[0] = 0;
        for ($k = 1; $k < $count2; $k++ )
        {
            $a2 = mysql_result($k2,$k-1,0);
            $b2 = mysql_result($k2,$k,0);                                    
            $k2_arr[$k] = (($b2-$a2)/$a2)*100;
        }                                
        $k3_arr[0] = 0;
        for ($l = 1; $l < $count3; $l++ )
        {
            $a3 = mysql_result($k3,$l-1,0);
            $b3 = mysql_result($k3,$l,0);                                    
            $k3_arr[$l] = (($b3-$a3)/$a3)*100;
        }
                  
        $dx1 = round($dlc,2);                          
        //$dx3 = round($rr*100,2);
        $dx5 = round((stdvep($g_arr)* sqrt(250)),2);
        $dx6 = round((stdvep($h_arr)* sqrt(250)),2);
        $dx7 = round((stdvep($i_arr)* sqrt(250)),2);
        $dx8 = round((stdvep($j_arr)* sqrt(250)),2);
        $dx9 = round((stdvep($k_arr)* sqrt(250)),2);
        $dx10 = round((stdvep($k2_arr)* sqrt(250)),2);
        $dx11 = round((stdvep($k3_arr)* sqrt(250)),2);
                                                            
        $dy1 = round(($loi_nh*100), 2);
        $dy5 = round((((mysql_result($row5col1,0,0))/100-1)*100),2);
        $dy6 =  round((((mysql_result($row5col1,0,1))/100-1)*100),2);
        $dy7 = round((((mysql_result($row5col1,0,2))/100-1)*100),2);
        $dy8 = round((($vn_ht/$vn_namtruoc-1)*100),2);
        $dy9 = round((($hn_ht/$hn_namtruoc-1)*100),2);
        $dy10 = round((($sp_ht/$sp_namtruoc-1)*100),2);
        $dy11 = round((($sh_ht/$sh_namtruoc-1)*100),2);                                    
                                                                                
        $datax = array($dx1, 31, 33, 34, $dx5, $dx6, $dx7, $dx8, $dx9, $dx10, $dx11);
        $datay = array($dy1, -22, -12, -13, $dy5, $dy6, $dy7, $dy8, $dy9, $dy10, $dy11);
        
        $graph = new Graph(420,250,"auto");
        $graph->SetScale("lin", -40, 30, 10, 40);
        $graph->SetBox(true);
        $graph->img->SetMargin(40,40,40,40);        
        $graph->SetShadow();
        $graph->title->Set('Biểu đồ lợi nhuận - Rủi ro');
        
        $graph->xaxis->SetTickPositions(array(10, 15, 20, 25, 30, 35, 40));
        $graph->xaxis->HideTicks(false);
        
        $graph->yaxis->SetTickPositions(array(-40, -30, -20, -10, 0, 10, 20, 30), array(-35, -25, -15, -5, 5, 15, 25));        
        $graph->ygrid->SetColor('gray');
        $graph->ygrid->SetFill(false);
        $graph->yaxis->HideLine(false);
        $graph->yaxis->HideTicks(false,false);
        
        $p1 = new ScatterPlot($datay,$datax);
        $p1->mark->SetType(MARK_FILLEDCIRCLE);
        $p1->mark->SetFillColor("blue");
        $p1->mark->SetWidth(3);
        
        $graph->Add($p1);
        $graph->Stroke();

        $this->view->graph = $graph;
    }
    
    public function graph7Action()
    {
    	global $config;
    	try{    		
		$request = $this->getRequest();        
        if(!($ticker = $request->getParam("id")))
        	$ticker = $config["default_stock"];           	
        $sql = mysql_query("SELECT cr.`hsrr`, cr.`stock_code` FROM `stock_date` st,`cal_risk` cr  WHERE cr.`stock_date_id` = st.`id` AND cr.`stock_code` = '".$ticker."'");        
        $hsrr = mysql_result($sql, 0, 0);        
        $stock_code = mysql_result($sql, 0, 1);
        
        $sql = "select `hsrr` from cal_risk order by `hsrr` LIMIT 9,1";
        $result = mysql_query($sql);
        $hsrr_10_max = mysql_result($result, 0, 0);
        
       	$max_x = round($hsrr,2);
       	if($hsrr_10_max > $hsrr)
       		$max_x = round($hsrr_10_max+0.01,2);
       		
       		
        // Create the graph. These two calls are always required
        $datay = array($hsrr);
        //d($datay);die;
        
        $graph = new Graph(200,30,'auto');
        $graph->SetScale("textlin",0,$max_x);
        $graph->yaxis->SetTickPositions(array(0.0, $max_x/2, $max_x ));                
        $graph->xaxis->SetTickLabels(array($stock_code));
        
        $graph->Set90AndMargin(0,0,17,5);
        $graph->img->SetAngle(90); 
        
        // set major and minor tick positions manually
        $graph->SetBox(false);
        $graph->ygrid->Show(false);
        $graph->ygrid->SetFill(false);
        $graph->yaxis->HideLine(false);
        $graph->yaxis->HideTicks(false,false);
        
        // For background to be gradient, setfill is needed first.
        //$graph->SetBackgroundGradient('#00CED1', '#FFFFFF', GRAD_HOR, BGRAD_PLOT);
        
        // Create the bar plots
        $b1plot = new BarPlot($datay);
        
        // ...and add it to the graPH
        $graph->Add($b1plot);
        
        $b1plot->SetWeight(0);
        $b1plot->SetFillGradient("red","red",GRAD_HOR);
        $b1plot->SetWidth(7);
        
        // Display the graph
        $graph->Stroke();
        $this->view->graph = $graph;
    	}catch(Exception $ex){
    		d($ex);
    	}
    }
    
    public function processAction(){
    	//$this->getRequest()->getParam('');
    	global $config;
    	
    	$this->_helper->layout->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    	    	
    	$param = $this->getRequest()->getParams();
    	$res = 0;
    	
    	$stocks = array();
    	$ratios = array();
    	
//    	
//    	    	
//    	//temporary. Connect db here. will replace with ini or config
//    	$db = Zend_Db::factory('Pdo_Mysql', array(
//    		'host' => '127.0.0.1',
//    		'username' => 'root',
//    		'password' => '',
//    		'dbname' => 'stock'    		    		    	
//    	));
//    	
//    	
		$db = Zend_Registry::get("connectDB");
				
    	$today = $config['today'];
    	$previous_year_time = strtotime("-1 year",$config["today_time"]);      	
    	$previous_year = date("Y-m-d",$previous_year_time);
    	
    	$ret_values = array();
		$port = array();		
				    	
	    for($i = 1 ; $i < 6;$i++){				
			$result_ret = array();
			if(!$param['custom_stock_'.$i] || !$param['custom_per_'.$i]){				
				continue;				
			}
				
			$sql = "SELECT `date`, `ret` from `stock_date` where `ticker`='{$param['custom_stock_'.$i]}' and `date` BETWEEN '{$previous_year}' AND '{$today}'";			
			$res = $db->fetchAll($sql);	
			if(count($res)==0){
				continue;
			}		
			foreach($res as $r){
				$result_ret[$r['date']] = $r['ret']; 				
			}
			
			$stocks[] = $param['custom_stock_'.$i];
			$ratios[] = $param['custom_per_'.$i];
			
			//$ret_values[$dm_index[$i][0]] = $result_ret;
			// index same as $retvalue
			$ret_values[] = $result_ret;
    	}
    	    
		$j = 0;
		if(array_sum($ratios)!=100){
			echo "{success: false, msg:'The portfolio should be 100%'}";
    		return ;
		}		
		// i: 0 ~> 4		
		
		$num_stock = count($ret_values);			
		foreach($ret_values[0] as $key=>$value){
			if(count($port)==0){
				$port[] = 1;
				continue;
			}
			$j++;
			$total = $value*$ratios[0]/100 +1;
			
			for($i = 1; $i < $num_stock; $i++){
				$total+=$ret_values[$i][$key]*$ratios[$i]/100;
			}			
							
			$total = $port[count($port)-1]*$total;		
			$port[] = $total;
		}

		$ret_port = array();
		$ret_port[] = 0;
		$n  = count($port);
		for($i = 1; $i < $n; $i++){
			$ret_port[] = $port[$i]/$port[$i-1]-1;
		}
		
	    $rr = stdvep($ret_port)*sqrt(250);    
	    $profit = $port[count($port)-1]-1;
	    
	    $str ="";
	    //$count=0;
	    /*
	    foreach ($stocks as $stock){
	    	$str.="'".$stock."':".$ratios[$count++]."',";
	    }
	    */
	    
	    $res = array();
	    $res['success'] = true;
	    $res['ruiro'] = round($rr*100,2);
	    $res['loinhuan'] = round($profit*100,2);
	    
	    echo json_encode($res);
	    
	    //$success_str = "[{'success': true, data:{},'ruiro':'{$rr}','loinhuan':'{$profit}'}]";
    	//echo $success_str ;
    	return;
    }    
}